#django imports
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms
from django.forms.util import ErrorList
from django.forms.fields import email_re

#python imports
import sys
import traceback
import urllib
import base64, string
import logging
import datetime
import mimetypes
import struct
import math
import random
import os
import pdb
import cgi
import operator

from StringIO import StringIO


# AppEngine imports
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.ext import search
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.api import images

#App imports
import models
import budget
import actual
import category
import appuser

arrMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']


    
def doLoginRequired(func):
  """Decorator that redirects to the login page if you're not logged in."""

  def login_wrapper(request, *args, **kwds):
    googleUser = users.get_current_user()
    if googleUser is None:
      return HttpResponseRedirect(
          users.create_login_url(request.get_full_path().encode('utf-8')))
    #user = appuser.GetUser()
    return func(request, *args, **kwds)

  return login_wrapper

def GetHtmlHeader(pTitle):
  """This gets html header"""
  html = '<html>\r\n'
  html += '<head>\r\n'
  html += '<link type="text/css" rel="stylesheet" href="static/app.css" />\r\n'
  html += '<script type="text/javascript" src="/static/app.js"></script>\r\n'
  html += '<title>' + pTitle + '</title>\r\n'
  html += '</head>\r\n'
  html += '<body id="AppBody">\r\n'
  html += '<form name="frmApp" method="post" action="">\r\n'
  html += '<div id="Overlay"></div>\r\n'
  return html

def GetHtmlFooter():

  html = '<hr class="TabLine" />\r\n'
  html += '<div align="center"><img src="http://code.google.com/appengine/images/appengine-noborder-120x30.gif"  border="0" alt="Powered by Google App Engine" /></div>\r\n'
  html += '</form>\r\n'
  html += '</body>\r\n'
  html += '</html>\r\n'
  return html

def GetHeaderHtml(pSelectedTab):
  """This gets the header html for a page."""
  user = appuser.GetUser()

  userName = user.GoogleUser.nickname() 
  if str(user.UserFirstName).lower() != 'none':
    userName = user.UserFirstName
    if str(user.UserLastName).lower() != 'none':
      userName += " " + user.UserLastName
  tab1 = '<a href="/">Home</a>'
  tab2 = '<a href="/categories">Categories</a>'
  tab3 = '<a href="/vendors">Vendors</a>'
  tab4 = '<a href="/profile">Profile</a>'
  
  if pSelectedTab == 'home':
    tab1 = '<b>Home</b>'
  elif pSelectedTab == 'categories':
    tab2 = '<b>Categories</b>'
  elif pSelectedTab == 'vendors':
    tab3 = '<b>Vendors</b>'
  elif pSelectedTab == 'profile':
    tab4 = '<b>Profile</b>'
  
  html = '<table width="99%" cellpadding="4" cellspacing="4">\r\n'
  html += '<tr>\r\n'
  html += '<td align="left" valign="middle"class="AppTitleXpense">Xpense<span class="AppTitleTrak">Trak!</a></td>\r\n'
  html += '<td align="right" valign="middle"><span class="Welcome1">Welcome</span> <span class="Welcome2">' + userName + '</span></td>\r\n'
  html += '</tr>\r\n'
  html += '</table>\r\n'
  html += '<table  cellpadding="0" cellspacing="0">\r\n'
  html += '<tr>\r\n'
  html += '<td class="Tab">' + tab1 + '</td>\r\n'
  html += '<td class="Tab">' + tab2 + '</td>\r\n'
  html += '<td class="Tab">' + tab3 + '</td>\r\n'
  html += '<td class="Tab">' + tab4 + '</td>\r\n'
  html += '</tr>\r\n'
  html += '</table>\r\n'
  html += '<hr class="TabLine" />\r\n'

  return html




def GetNewCategoryDialog():
  """This gets new category dialog (absolute div). """
  html = ''
  html += '<div id="NewExpCatDialog">\r\n'
  html += '<table border="0" cellpadding="2" cellspacing="0" width="100%" height="100%">\r\n'
  html += '<tr>\r\n'
  html += '<td class="Header">New Expense Category</td>\r\n'
  html += '</tr>\r\n'
  html += '<tr>\r\n'
  html += '<td class="Body">\r\n'
  html += '<div id="divNewExpCatLabel" align="left" style="color:black;padding:4px 4px 4px 4px;">Please enter a new expense category:</div>\r\n'
  html += '<div align="left" style="padding:4px 4px 4px 4px;"><input id="txtNewExpCat" name="txtNewExpCat" class="textbox1" type="text" value="" size="65" /></div>\r\n'
  html += '<div align="right" style="padding:4px 4px 4px 4px;"><input id="btnNewExpCatOk" name="btnNewExpCatOk" class="button" type="button" value="OK" onclick="doAddNewExpCat()"  />\r\n'
  html += '<input id="btnNewExpCatCancel" name="btnNewExpCatCancel" class="button" type="button" value="Cancel" onclick="doHideNewExpCatDialog()" /></div>\r\n'
  html += '</td>\r\n'
  html += '</tr>\r\n'
  html += '</table>\r\n'
  html += '</div>\r\n'
 

  return html



@doLoginRequired
def doAddCategoryRequest(request):

  user = appuser.GetUser()
  categoryDao = category.CategoryDao()
  r = HttpResponse()

  if request.method == 'GET':
    if request.GET['catname']:
      catname = request.GET['catname'].lower()
    else:
      catname = ''  

    if (catname == ''):
      r.write('failure')
    else:
      if categoryDao.doCheckIfCategoryExists(catname):
        r.write('duplicate')
      else:
        categoryResult = categoryDao.doAddCategory(user, catname)
        r.write(catname.upper())
  
  return r
  
@doLoginRequired
def GetHomePage(request):

  categoryDao = category.CategoryDao()

  r = HttpResponse()

  if request.method == 'POST':
    newExpCat = request.POST['ddlNewExpCategory'].lower()
    action = request.POST['txtBudgetAction'].lower()
    year = int(str(request.POST['ddlBudgetYear']))
    budgetDao = budget.BudgetDao()
    if action == 'savebudget':
      if len(newExpCat) > 0:
        user = appuser.GetUser()
        if not categoryDao.doCheckIfCategoryExists(newExpCat):
          categoryResult = categoryDao.doAddCategory(user, newExpCat)
        else:
          categoryResult = categoryDao.GetCategory(newExpCat)
          
        janExp=float(str(request.POST['txtJanNewB']))
        febExp=float(str(request.POST['txtFebNewB']))
        marExp=float(str(request.POST['txtMarNewB']))
        aprExp=float(str(request.POST['txtAprNewB']))
        mayExp=float(str(request.POST['txtMayNewB']))
        junExp=float(str(request.POST['txtJunNewB']))
        julExp=float(str(request.POST['txtJulNewB']))
        augExp=float(str(request.POST['txtAugNewB']))
        sepExp=float(str(request.POST['txtSepNewB']))
        octExp=float(str(request.POST['txtOctNewB']))
        novExp=float(str(request.POST['txtNovNewB']))
        decExp=float(str(request.POST['txtDecNewB']))

        
        budgetExpCategory = budgetDao.doAddBudgetExpenseByCategory(user.key(), year, categoryResult.key(), 1,
                                               janExp, febExp, marExp, aprExp, mayExp, junExp, julExp,
                                               augExp, sepExp, octExp, novExp, decExp, False)


      # Saves existing budget
      index = int(str(request.POST['txtBudgetIndex']))
      if (index > 0):     
        
        for j in range(index):
          i = j + 1;
          budgetExpCatKey = db.Key(str(request.POST['txtBudgetCatKey' + str(i)]))
          catName = str(request.POST['txtExpCatName' + str(i)])
          janExp=float(str(request.POST['txtJanB' + str(i)]))
          febExp=float(str(request.POST['txtFebB' + str(i)]))
          marExp=float(str(request.POST['txtMarB' + str(i)]))
          aprExp=float(str(request.POST['txtAprB' + str(i)]))
          mayExp=float(str(request.POST['txtMayB' + str(i)]))
          junExp=float(str(request.POST['txtJunB' + str(i)]))
          julExp=float(str(request.POST['txtJulB' + str(i)]))
          augExp=float(str(request.POST['txtAugB' + str(i)]))
          sepExp=float(str(request.POST['txtSepB' + str(i)]))
          octExp=float(str(request.POST['txtOctB' + str(i)]))
          novExp=float(str(request.POST['txtNovB' + str(i)]))
          decExp=float(str(request.POST['txtDecB' + str(i)]))

          budgetExpCategory = budgetDao.doUpdateBudgetExpenseByCategory(budgetExpCatKey, janExp, febExp, marExp, aprExp, mayExp, junExp,
                                                                         julExp, augExp, sepExp, octExp, novExp, decExp)
          
  
  html = GetHtmlHeader('XpenseTrak')
  html += GetHeaderHtml('home')
  html += budget.GetBudgetExpenseByCategories(2009)
  html += GetNewCategoryDialog()
  html += GetHtmlFooter()
  r.write(html)
  
  return r

@doLoginRequired
def GetActualExpByCatPage(request):
  r = HttpResponse()
  html = GetHtmlHeader('XpenseTrak')
  html += GetHeaderHtml('home')
  html += actual.GetActualExpenseByCategories(2009)
  html += GetHtmlFooter()
  r.write(html)
  return r

@doLoginRequired
def GetProfilePage(request):
  r = HttpResponse()
  r.write(GetHtmlHeader('XpenseTrak > Profile'))
  r.write(GetHeaderHtml('profile'))
  r.write(GetHtmlFooter())
  return r

@doLoginRequired
def GetCategoriesPage(request):
  r = HttpResponse()
  r.write(GetHtmlHeader('XpenseTrak > Categories'))
  r.write(GetHeaderHtml('categories'))
  r.write(GetHtmlFooter())
  return r

@doLoginRequired
def GetVendorsPage(request):
  r = HttpResponse()
  r.write(GetHtmlHeader('XpenseTrak > Vendors'))
  r.write(GetHeaderHtml('vendors'))
  r.write(GetHtmlFooter())
  return r



